<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import {ComponentInternalInstance, getCurrentInstance, onMounted, ref, Ref} from "vue";
import { getLastPathSegment } from './utils.ts'
import menuListStore from "../stores/menuListStore.ts";

interface Breadcrumb {
  title: string;
  icon?: string;
  path: string;
}

interface MenuItem {
  path: string;
  name: string;
  icon: string;
  children?: MenuItem[];
}

const menuList = menuListStore()
const breadcrumb: Ref = ref([]);
const route = useRoute();
const router = useRouter()
const { appContext } = <ComponentInternalInstance>getCurrentInstance()
const icons = appContext.config.globalProperties.$antIcons
const flattenedMenuList = flattenMenuList(menuList.list);


/**
 * @description 将菜单数组扁平化
 * @param menuList
 */
function flattenMenuList(menuList: MenuItem[]): MenuItem[] {
  const flattenedList: MenuItem[] = [];

  for (const item of menuList) {
    flattenedList.push(item);

    if (item.children && item.children.length > 0) {
      const flattenedChildren = flattenMenuList(item.children);
      flattenedList.push(...flattenedChildren);
    }
  }

  return flattenedList;
}

/**
 * @description 根据path获取相应的icon（需要扁平化后的菜单array）
 * @param menuList
 * @param path
 */
function getIconByPath(menuList: MenuItem[], path: string): string | undefined {
  const menuItem = menuList.find(item => item.path === path);
  return menuItem ? menuItem.icon : '';
}

function extractText() {
  breadcrumb.value = []
  const matched = route.matched;
  const newBreadcrumbs: Breadcrumb[] = [];

  for (let i = 0; i < matched.length; i++) {
    const { name, path } = matched[i];
    const icon = getIconByPath(flattenedMenuList, getLastPathSegment(path))
    if (name && path){
      newBreadcrumbs.push(<Breadcrumb>{title: name, path, icon});
    }
  }
  breadcrumb.value.push(...newBreadcrumbs);
}



onMounted(()=>{
  router.afterEach(()=>{
    extractText();
  })
  extractText();
})
</script>

<template>
  <a-breadcrumb style="margin: 10px 0">
    <a-breadcrumb-item v-for="item in breadcrumb">
      <component :is="icons[item.icon]" />
      <span>{{item.title}}</span>
    </a-breadcrumb-item>
  </a-breadcrumb>
</template>

<style scoped>

</style>